<!--
  文件名: UserInfo.vue
  描述: 这是一个用户信息界面，用于用户信息和文章查看，用户日常查看。参考界面为B站
  作者: 白紫铜
  创建日期: 2024-03-21
-->
<template>
  <div class="userinfo">
    <el-container>
      <el-aside class="aside" width="150px"></el-aside>
      <el-container>
        <el-header class="header">
          <el-col :span="24" class="userinfo_col_0">
            <el-avatar :size="100" :src="imageUrl"></el-avatar>
            <div class="userinfo-info">
              <div class="userinfo-username">{{ username }}<span style="margin: 0 10px"></span>
                <span><el-icon v-show="ShowMale"><Male /></el-icon></span>
                <span><el-icon v-show="ShowFemale"><Female /></el-icon></span>
                <span v-show="ShowSecret" style="font-size: 16px">保密</span>
                <div v-show="ShowOtherUserSetting" style="display: flex; justify-content: flex-end; width: 800px">
                  <el-button @click="createFollow" v-if="!isFollowed" class="button_left">关注</el-button>
                  <el-button @click="deleteFollow" v-if="isFollowed" class="button_left"><el-icon><Check /></el-icon>已关注</el-button>
                  <el-button class="button_left">私信</el-button>
                </div>
              </div>
              <div style="margin-bottom: 20px"></div>
              <div class="userinfo-introduce">{{ introduce }}</div>
            </div>
          </el-col>
        </el-header>
        <el-main class="main">
          <el-row>
            <el-col :span="17" class="user-info-col_2">
              <el-tabs class="tabs_0" type="card">
                <el-tab-pane label="博客">
                  <el-row v-for="blog in blogs" :key="blog.id">
                    <div class="blog-info">
                      <img :src="blog.coverUrl" alt="博客封面" style="display: flex; height: 135px;width: 240px;align-items: center;text-align: center">
                      <div class="blog-info-details">
                        <el-link @click="gotoBlogDetails(blog)" class="blog-info-title">{{ blog.title }}</el-link>
                        <div class="blog-info-description">{{ blog.summary }}</div>
                        <div class="blog-info-author">作者：{{ blog.author.username }}</div>
                        <div class="blog-info-created-at">创建时间：{{ formatDate(blog.createdAt) }}</div>
                        <span class="blog-info-created-at">标签：{{ blog.tags }}</span>
                      </div>
                    </div>
                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="收藏"></el-tab-pane>
              </el-tabs>
            </el-col>
            <span style="margin: 0 10px"></span>
            <el-col :span="6" class="user-info-col_3" >
              <el-link :underline="false" class="link_left">关注{{counts[0]}}</el-link>
              <el-link :underline="false" class="link_left">粉丝{{counts[1]}}</el-link>
              <div style="margin-bottom: 50px"></div>
              <div v-show="ShowUserSetting">
                <el-button class="button_left" @click="gotoBlogWriting">发表文章</el-button>
                <el-button class="button_left">内容管理</el-button>
              </div>
              <div style="margin-top: 50px"></div>
              <el-divider></el-divider>
              <div>UID:{{userinfo.user_id}}</div>
              <div style="margin: 25px"></div>
              <div>生日:{{userinfo.birthday}}</div>
              <div style="margin-bottom: 50px"></div>
            </el-col>
          </el-row>
          <div ref="loadMoreTrigger" style="height: 10px;"></div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>

import defaultAvatar from "@/assets/defaultAvatar.png";
import axios from "axios";
import {Check, Female, Male} from "@element-plus/icons-vue";
export default {
  name: 'SelfUserInfo',
  components: {Check, Female, Male},
  props: {
    msg: String
  },
  data(){
    return{
      selectedFile:null,
      imageUrl:defaultAvatar,
      username:"",//页面用户的用户名
      introduce:"这个人很懒，没有写介绍",
      userName:"",
      blogs:[],
      page:0,
      pageSize:10,
      loading:false,
      user_id:"",//页面用户的用户id
      observer: null,
      ShowUserSetting:false,
      ShowOtherUserSetting:true,
      userinfo:[],
      ShowFemale:false,
      ShowMale:false,
      ShowSecret:false,
      isFollowed:false,
      counts:[],
    }
  },
  created() {
    this.userName=decodeURIComponent(this.$route.params.user)
    console.log(this.userName)
  },
  mounted() {
    this.fetchUserInfo().then(() => {
      if(this.userName===localStorage.getItem("username")){
        this.ShowUserSetting=true;
        this.ShowOtherUserSetting=false;
      }
      this.fetchFollow()
      this.getFollowCount()
      // 初始化 Intersection Observer
      this.observer = new IntersectionObserver(this.handleIntersection, {
        root: null,
        rootMargin: '0px',
        threshold: 0.1, // 当目标元素的10%进入视口时触发回调
      });

      // 监听加载更多数据的元素
      this.observer.observe(this.$refs.loadMoreTrigger);
    });
  },
  beforeUnmount() {
    // 销毁 Intersection Observer
    if (this.observer) {
      this.observer.disconnect();
    }
  },
  methods:{
    fetchFollow(){
      const token=localStorage.getItem("token")
      axios.get("http://localhost:1145/api/get_follow",{
        headers:{
          Authorization:`Bearer ${token}`
        },
        params:{
          follower_id:localStorage.getItem('user_id'),
          followed_id:this.user_id
        }
      }).then(response=>{
        console.log(response.data)
        if(response.data==="ok"){
          this.isFollowed=true
        }
        if(response.data==="fail"){
          this.isFollowed=false
        }
      }).catch(error=>{
        console.log(error)
      })
    },

    fetchUserInfo() {
      return new Promise((resolve, reject) => {
        const token = localStorage.getItem('token');
        axios.get('http://localhost:1145/userinfo', {
          headers: {
            Authorization: `Bearer ${token}`
          },
          params:{
            username:this.userName
          }
        })
            .then(response => {
              this.userinfo = response.data;
              this.user_id = this.userinfo.user_id;
              this.username = this.userinfo.username;
              this.imageUrl = this.userinfo.avatarUrl;
              this.introduce = this.userinfo.introduce;
              if(this.userinfo.sex==="male"){
                this.ShowMale=true;
              }
              if(this.userinfo.sex==="female"){
                this.ShowMale=true;
              }if(this.userinfo.sex==="serect"){
                this.ShowSecret=true;
              }
              console.log('获取用户信息成功');
              resolve(); // 表示fetchUserInfo成功执行
            })
            .catch(error => {
              this.$message.error('权限不足');
              this.$router.push({
                name: 'HomePage'
              });
              console.log('获取用户信息失败', error);
              reject(error); // 表示fetchUserInfo执行出错
            });
      });
    },
    fetchBlogs(){
      axios.get("http://localhost:1145/blogs",{
        params:{
          page:this.page,
          pageSize:this.pageSize,
          author_id:this.user_id,
        }
      }).then(response=>{
        this.blogs=this.blogs.concat(response.data.content)
        this.page++
        this.loading=false
      }).catch(error => {
        console.error('获取博客数据失败', error);
        this.loading = false;
      });
    },
    formatDate(dateTime) {
      const date = new Date(dateTime);
      // 获取日期的年、月和日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并且确保是两位数
      const day = String(date.getDate()).padStart(2, '0'); // 日，确保是两位数

      // 拼接成日期格式
      return `${year}-${month}-${day}`;
    },
    // Intersection Observer 回调函数
    handleIntersection(entries) {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 当加载更多数据的元素进入视口时，加载更多数据
          this.fetchBlogs();
        }
      });
    },
    gotoBlogWriting(){
      this.$router.push({name:"BlogWriting",params:{
          user:encodeURIComponent(this.username)
        }})
    },
    gotoBlogDetails(blog){
      this.$router.push({
            name:"BlogDetails",
            params:{
              user_id:blog.author.user_id,
              post_id:blog.id,
              title:encodeURIComponent(blog.title) // 编码标题，以防止特殊字符对路由造成影响
            }
          }
      )
    },
    createFollow(){
      const token=localStorage.getItem("token")
      axios.post("http://localhost:1145/api/create_follow",{
        follower_id:localStorage.getItem("user_id"),
        followed_id:this.user_id
      },{
        headers:{
          Authorization:`Bearer ${token}`
        }
      }).then(response=>{
        console.log(response.data)
        this.$message.success("关注成功")
        this.isFollowed=true
        this.getFollowCount()
      }).catch(error=>{
        console.log(error)
        this.$message.error("关注失败")
      })
    },
    deleteFollow(){
      const token=localStorage.getItem("token")
      axios.delete("http://localhost:1145/api/delete_follow",{
        headers:{
          Authorization:`Bearer ${token}`
        },
        params:{
          follower_id:localStorage.getItem("user_id"),
          followed_id:this.user_id
        }
      }).then(response=>{
        console.log(response.data)
        this.fetchFollow()
        this.getFollowCount()
        this.$message.success("取消关注成功")
      })
    },
    getFollowCount(){
      axios.get("http://localhost:1145/get_follow_count",{
        params:{
          user_id:this.user_id
        }
      }).then(response=>{
        this.counts=response.data
      })
    }
  }
}
</script>

<style scoped>
.aside{
  background-color: #ffffff;
  width: 200px;
  height: 100%
}
.header{
  width: 1050px;
  height: 300px;
  display: flex;
  align-items: flex-end;
  background-image: url("@/assets/userBackgroundImage/DefaultBackground.png");
  background-size: cover;/* 填充容器 */
  background-position: center;
}
.main{
  width: 1050px;
}
.userinfo_col_0{
  width: 100%;
  height: 100px;
  display: flex; /* 使用 Flex 布局 */
  align-items: center; /* 垂直居中头像和用户名 */
}
.userinfo-username {
  width: 200px;
  font-size: 20px;
  color: #ffffff;
  font-weight: bold;
}
.userinfo-introduce{
  width: 200px;
  font-size: 16px;
  color: #ffffff;
  font-weight: bold;
}
.userinfo-info {
  margin-left: 20px; /* 可根据需要调整头像和用户名之间的间距 */
  width: 1000px;
}
.user-info-col_2{
  width: 100%;
  height: 100%;
  background-color: #F5F7FA;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
}

.blog-info {
  display: flex;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
}

.blog-info img {
  width: 150px;
  height: auto;
  margin-right: 20px;
}

.blog-info-details {
  flex-grow: 1;
}

.blog-info-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
}

.blog-info-description {
  margin-bottom: 10px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  width: 50ch; /* 最多显示15个字符 */
}


.blog-info-meta {
  display: flex;
  justify-content: space-between;
}

.blog-info-author,
.blog-info-created-at{
  font-size: 14px;
  color: black;
}
.blog-info-description {
  margin-top: 10px;
}
:deep(.el-tabs--card>.el-tabs__header .el-tabs__item.is-active){
  color: #606266 !important;
  font-weight: bold;
}
:deep(.el-tabs--card>.el-tabs__header .el-tabs__item:not(.is-disabled):hover){
  color: #606266 !important;
  background-color: #ffffff;
}
.user-info-col_3{
  width: 100%;
  height: 100%;
  background-color: #F5F7FA;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
  text-align: center;
}
.link_left{
  margin-right: 10px;
  transition: 0.3s ease;
}
.link_left:hover{
  color: #303133;
  font-weight: bold;
}
.button_left{
  border-radius: 0;
  background-color: black;
  color: white;
  transition: 0.3s ease;
  border-color: black;
}
.button_left:hover{
  background-color: #606266;
  color: #ffffff;
  border-color: #606266;
}
.button_left:focus{
  background-color: #606266;
  color: #ffffff;
  border-color: #606266;
}
.el-link{
  color: black;
  text-decoration: none !important;
}
.el-link:hover{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
.el-link::after{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
</style>